package com.yhk.wuchat.common.common.exception;

import com.yhk.wuchat.common.common.domain.vo.resp.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/4/9 16:49
 * @注释
 */

/**
 * 全局异常捕获
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 参数错误异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ApiResult<?> methodArgumentNotValidException(MethodArgumentNotValidException e){
        StringBuilder errMsg=new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(fieldError -> {
            errMsg.append(fieldError.getField()).append(fieldError.getDefaultMessage()).append(",");
        });
        String message = errMsg.toString();
        return ApiResult.fail(CommonErrorEnum.PARAM_INVALID.getCode(),message.substring(0,message.length()-1));
    }

    @ExceptionHandler(value= Throwable.class)
    public ApiResult<?> throwable(Throwable e){
        log.error("系统异常",e.getMessage(),e);
        return ApiResult.fail( CommonErrorEnum.SYSTEM_ERROR);
    }

    @ExceptionHandler(value= BusinessException.class)
    public ApiResult<?> businessException(BusinessException e){
        log.info("业务异常",e);
        return ApiResult.fail(e.getErrorCode(),e.getErrorMsg());
    }

}
